import time

from flask import Flask, render_template, request,session,redirect,jsonify
import json
from . import strategy
import os
from frameworks.cores.Config import *
from frameworks.utils.JsonResult2 import *
from frameworks.cores.LoadClass import *
import akshare as ak
from flask import Flask, render_template
from pyecharts.charts import Line
from pyecharts import options as opts
import pandas as pd
import sqlite3
import re

basepath = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
config = Config(basepath)

apimap = config.getApi()
env = apimap["base"]
print(env)
from flask_session import Session

jsonResult = JsonResult2()

loader = LoadClass()

import datetime
import time

# 初始化数据库
def init_db():
    conn = sqlite3.connect('database.db')
    c = conn.cursor()
    c.execute('''CREATE TABLE IF NOT EXISTS strategies
                 (id INTEGER PRIMARY KEY AUTOINCREMENT, components TEXT)''')
    conn.commit()
    conn.close()

def remove_sublist_items(main_list, sub_list):
    return [item for item in main_list if item not in sub_list]

@strategy.route("/generate")
def generate():
    #init_db()
    return render_template("strategy/generate.html")

# 提交策略路由
# 验证策略组件
def validate_strategy_components(components):
    # 简单验证，确保组件不为空且符合一定格式
    valid_pattern = re.compile(r'^(买入信号|卖出信号|止损条件|止盈条件): [\w\s]+$')
    for component in components:
        if not component or not valid_pattern.match(component):
            return False
    return True

# 提交策略路由
@strategy.route('/submit-strategy', methods=['POST'])
def submit_strategy():
    data = request.get_json()
    components = data.get('components')[2:]
    print(components)

    if not components:
        return jsonify({'message': '策略组件不能为空'}), 400
    #if not validate_strategy_components(components):
    #    return jsonify({'message': '策略组件格式不正确'}), 400

    components_str = ','.join(components)
    conn = sqlite3.connect('database.db')
    c = conn.cursor()
    c.execute("INSERT INTO strategies (components) VALUES (?)", (components_str,))
    conn.commit()
    conn.close()

    try:
        execute_strategy(components)
        return jsonify({'message': '策略提交成功'})
    except Exception as e:
        return jsonify({'message': f'策略执行失败: {str(e)}'}), 500

# 查看策略路由
@strategy.route('/view-strategies')
def view_strategies():
    conn = sqlite3.connect('database.db')
    c = conn.cursor()
    c.execute("SELECT id, components FROM strategies")
    strategies = [{'id': row[0], 'components': row[1]} for row in c.fetchall()]
    subStrategies = []
    for option in strategies[0]["components"].split(","):
        subStrategies.append(option)
    conn.close()
    strategyGroup = ["买入信号：均线金叉","卖出信号：均线死叉","止损条件：亏损 5%","止盈条件：盈利 10%"]
    newList = remove_sublist_items(strategyGroup,subStrategies)
    return render_template('strategy/view_strategies.html', newList=newList, strategies=strategies)

# 更新策略路由
@strategy.route('/update-strategies', methods=['POST'])
def update_strategies():
    data = request.get_json()
    strategies = data.get('strategies')
    if not strategies:
        return jsonify({'message': '未提供有效的策略信息'}), 400

    conn = sqlite3.connect('database.db')
    c = conn.cursor()
    for strategy in strategies:
        strategy_id = strategy.get('id')
        components = strategy.get('components')
        #if not components or not validate_strategy_components(components):
        #    conn.close()
        #    return jsonify({'message': f'策略 ID {strategy_id} 组件格式不正确'}), 400
        components_str = ','.join(components)
        c.execute("UPDATE strategies SET components = ? WHERE id = ?", (components_str, strategy_id))
    conn.commit()
    conn.close()

    try:
        for strategy in strategies:
            execute_strategy(strategy.get('components'))
        return jsonify({'message': '策略更新成功'})
    except Exception as e:
        return jsonify({'message': f'策略执行失败: {str(e)}'}), 500

# 模拟执行策略和调用交易接口
def execute_strategy(components):
    print("开始执行策略：", components)
    # 这里可以添加与真实交易接口的集成代码
    # 以下是简单模拟交易接口调用
    for component in components:
        if '买入信号' in component:
            print(f"根据 {component}，执行买入操作")
        elif '卖出信号' in component:
            print(f"根据 {component}，执行卖出操作")
        elif '止损条件' in component:
            print(f"根据 {component}，检查是否触发止损")
        elif '止盈条件' in component:
            print(f"根据 {component}，检查是否触发止盈")
    print("模拟调用交易接口进行交易操作...")
